class CreatePriceLists < ActiveRecord::Migration
  def self.up
    create_table :price_lists do |t|
      t.string      :name
      t.timestamps
    end
    load_from_csv("price_lists", price_list_data)
  end
  
  def self.load_from_csv(table_name, data)
    column_clause = nil
    is_header = false
    cnx = ActiveRecord::Base.connection
    ActiveRecord::Base.silence do
      reader = CSV::Reader.create(data)

      columns = reader.shift.map {|column_name| cnx.quote_column_name(column_name) }
      column_clause = columns.join(', ')

      reader.each do |row|
        next if row.first.nil? # skip blank lines
        raise "No table name defined" if !table_name
        raise "No header defined" if !column_clause
        values_clause = row.map {|v| cnx.quote(v).gsub('\\n', "\n").gsub('\\r', "\r") }.join(', ')
        sql = "INSERT INTO #{table_name} (#{column_clause}) VALUES (#{values_clause})"
        cnx.insert(sql)
      end
    end
  end

  def self.price_list_data
  <<'END_OF_DATA'
"id","name","created_at","updated_at"
1,"default","",""
END_OF_DATA
  end

  def self.down
    drop_table :price_lists
  end
end
